package com.example.logindb.controller;

import com.example.logindb.dto.UserDTO;
import com.example.logindb.sevices.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;


import java.util.Collection;

@Controller
public class LoginController {

    private final UserService userService;
    @Autowired
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @InitBinder
    public void removeWhiteSpaces(WebDataBinder dataBinder){
        StringTrimmerEditor st = new StringTrimmerEditor(true);
        dataBinder.registerCustomEditor(String.class, st);
    }

    @GetMapping("/")//已经有了身份认证后
    public String home(Authentication authentication) {

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities ) {
            if (grantedAuthority.getAuthority().equals("USER")) {
                return "redirect:/home";
            }
            else {
                return "redirect:/dashboard";
            }
        }
        System.out.println("判断身份权限，正在执行打开登录界面");
        return "redirect:/login";
    }

    @GetMapping("/login")//判断有无身份认证
    public String showLoginPage( Authentication authentication ) {


        if(authentication!=null)
        {return "redirect:/";}
        return "LoginPage";

    }


}
